package com.hanggold.jfinal.springboot.lesson1.service;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 *
 * @author <a href="mailto:sunmch@163.com">smc</a>
 * @date 2021-05-09 08:11
 * @since 1.0.0
 **/
@Component
public class LockService {

	private RedissonClient redissonClient;

	public LockService() {
		Config config = new Config();
		config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("soul");
		redissonClient = Redisson.create(config);
	}

	public void lock(String name) {
//		RLock lock = getTryLock(name);
		RLock lock = getLock(name);
//		System.out.println(lock == lock1);
//		lock.lock(10000L,TimeUnit.SECONDS);
		lock.lock();
	}

	public boolean tryLock(String name) {
		RLock lock = getTryLock(name);
		try {
			return lock.tryLock(0, 10000L, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
			Thread.currentThread().interrupt();
		}
		return false;
	}

	private RLock getLock(String name) {
		return redissonClient.getLock(name);
	}

	private RLock getTryLock(String name) {
		return redissonClient.getFairLock(name);
	}

	public void unTrylock(String name) {
		RLock lock = getTryLock(name);
		lock.unlock();
	}

	public void unlock(String name) {
		RLock lock = getLock(name);
		lock.unlock();
	}
}
